﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.ServiceModel.Syndication;
using Common.Library;
using Facebook;
using Facebook.Client;
using Facebook.Reflection;
using TweetSharp;
using TweetSharp.Model;
using System.ComponentModel;
using System.Threading;
using System.Collections.ObjectModel;
using Common.Utilities;
using System.Windows.Media;
using System.Windows.Controls.Primitives;

namespace Social_Celebrities
{
    public class DataItems
    {
        public object item
        {
            get;
            set;
        }
        public object comments
        {
            get;
            set;
        }
    }
    public partial class feedPage : PhoneApplicationPage
    {
        public AutoResetEvent auto = new AutoResetEvent(false);
        List<DataItems> DataSource = new List<DataItems>();
        string BlogComment = string.Empty;
        public string FeedType = string.Empty;
        public object CommentBox = default(object);
        public feedPage()
        {
            InitializeComponent();
            Loaded += feedPage_Loaded;
            LoadAds();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            NavigationContext.QueryString.TryGetValue("FeedType", out FeedType);
        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, FeedAd, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In feedPage.xaml.cs file file", ex);
                string excepmess = "Exception in LoadAds Method In feedPage.xaml.cs file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        void feedPage_Loaded(object sender, RoutedEventArgs e)
        {            
            try
            {
                if (FeedType == "FaceBook")
                {                   
                    DataItems d = new DataItems();
                    FaceListBox.Visibility = Visibility.Visible;
                    d.item = (SyndicationItem)Constants.SelectedSyndicationItem[0];
                    if (((ObservableCollection<commentsclass>)Constants.SelectedSyndicationItem[1]).Count == 0)
                        d.comments = null;
                    else
                    {
                        d.comments = (ObservableCollection<commentsclass>)Constants.SelectedSyndicationItem[1];                        
                    }
                    DataSource.Add(d);
                    FaceListBox.ItemsSource = DataSource;
                    string Link = ((SyndicationItem)d.item).Links.FirstOrDefault().Uri.ToString();
                }
                else if (FeedType == "Twitter")
                {
                    ObservableCollection<TwitterStatus> TwitterComments = new ObservableCollection<TwitterStatus>();
                    DataItems d = new DataItems();
                    TweetListBox.Visibility = Visibility.Visible;
                    d.item = (TwitterStatus)Constants.SelectedSyndicationItem[0];
                    TwitterLoginPage p = new TwitterLoginPage();
                    var service = new TwitterService("LYTy3T8P556GxqRymimhwA", "5TSKipEjESOAcdBsViWm2E1RVxFEN1Ooh0nRwIj7RsY");
                    string[] Tokens = new string[2];
                    Tokens = p.ReturnTokens(p.getAccessToken());
                    service.AuthenticateWith(Tokens[0], Tokens[1]);
                    service.Retweets(new RetweetsOptions() { Id = ((TwitterStatus)d.item).Id }, (ts1, rep1) =>
                    {
                        if(rep1.StatusCode == HttpStatusCode.OK)
                        {
                            Deployment.Current.Dispatcher.BeginInvoke((Action)(() =>
                                   {
                                       foreach (TwitterStatus si1 in ts1)
                                       {
                                           TwitterComments.Add(si1);
                                       }
                                       if (TwitterComments.Count == 0)
                                           d.comments = null;
                                       else
                                           d.comments = TwitterComments;
                                       DataSource.Add(d);
                                       TweetListBox.ItemsSource = DataSource;
                                   }));
                        }
                    });
                }
                else
                {
                    BlogListBox.Visibility = Visibility.Visible;
                    DataItems d = new DataItems();
                    d.item = (SyndicationItem)Constants.SelectedSyndicationItem[0];
                    DataSource.Add(d);
                    BlogListBox.ItemsSource = DataSource;
                }
                AppSettings.BackgroundAgenError = "feedPage_Loaded Method in feedpage.xaml.cs is Successfull..!!!";
            }
            catch (Exception ex)
            {
               // Exceptions.SendErrortoMail("Exception at feedPage_Loaded Method in feedPage.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at feedPage_Loaded Method in feedPage.xaml.cs", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void btnPost_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string PostId = string.Empty;
                var fb = new FacebookClient(AppSettings.FaceBookAccessToken);
                string Link = ((SyndicationItem)DataSource[0].item).Links.FirstOrDefault().Uri.ToString();

                if (Link.Contains("fbid="))
                {
                    PostId = Link.Substring(Link.IndexOf('=') + 1, ((Link.IndexOf('&') - 1) - Link.IndexOf('=')));
                }
                else if (Link.Contains("?type=1") || Link.Contains("&type=1"))
                {
                    string lin = Link.Replace("/?type=1", "").Replace("?set=", "").Replace("&type=1", "");
                    PostId = lin.Substring(lin.LastIndexOf('/') + 1);
                }
                else if (Link.Contains("video.php?v="))
                {
                    PostId = Link.Substring(Link.LastIndexOf("?v=") + 3);
                }
                else
                {
                    PostId = Link.Substring(Link.LastIndexOf('/') + 1);
                }
                fb.PostCompleted += (o, args) =>
                {
                    if (args.Error != null)
                    {
                        Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message));
                        return;
                    }
                    var result = (IDictionary<string, object>)args.GetResultData();
                    Dispatcher.BeginInvoke(() =>
                    {
                        //MessageBox.Show("Comment Posted successfully");
                        //(CommentBox as TextBox).Text = string.Empty;
                        Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                        TextBlock tb = frameBorder.FindName("Blog_Msg") as TextBlock;
                        tb.Text = "Comment posted successfully";
                        Popup Adc = frameBorder.FindName("pop") as Popup;
                        Adc.IsOpen = true;
                        NavigationService.GoBack();
                    });
                };
                var parameters = new Dictionary<string, object>();
                parameters["message"] = (CommentBox as TextBox).Text;
                fb.PostAsync("/" + PostId + "/comments", parameters);
            }
            catch(Exception ex)
            {
                //Exceptions.SendErrortoMail("Exception at btnPost_Click in facebook comment post Method in feedPage.xaml.cs Page and the error is " + " " + ex.Message + " " + ex.StackTrace);
                Exceptions.SaveOrSendExceptions("Exception at btnPost_Click in facebook comment post Method in feedPage.xaml.cs", ex);
                AppSettings.BackgroundAgenError = ex.Message;
            }
        }

        private void btnPost1_Click(object sender, RoutedEventArgs e)
        {
            TwitterLoginPage p = new TwitterLoginPage();
            var service = new TwitterService("LYTy3T8P556GxqRymimhwA", "5TSKipEjESOAcdBsViWm2E1RVxFEN1Ooh0nRwIj7RsY");
            string[] Tokens = new string[2];
            Tokens = p.ReturnTokens(p.getAccessToken());
            service.AuthenticateWith(Tokens[0], Tokens[1]);
            service.SendTweet(new SendTweetOptions { InReplyToStatusId = ((TwitterStatus)DataSource[0].item).Id, Status = "@" + ((TwitterStatus)DataSource[0].item).User.ScreenName + " " + (CommentBox as PhoneTextBox).Text }, tweetResponse);
        }
        
        private void tweetResponse(TwitterStatus tweet, TwitterResponse response)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Dispatcher.BeginInvoke(() => 
                { 
                  //MessageBox.Show("Tweet posted successfully"); 
                    Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                    TextBlock tb = frameBorder.FindName("Blog_Msg") as TextBlock;
                    tb.Text="Tweet posted successfully";
                    Popup Adc = frameBorder.FindName("pop") as Popup;
                    Adc.IsOpen = true;
                  NavigationService.GoBack();
                });
                //NavigationService.GoBack();
            }
            else
            {
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Authentication error"); NavigationService.GoBack(); });                   
                }
                else
                {
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); NavigationService.GoBack(); });                    
                }
            }
        }

        private void btnPost2_Click(object sender, RoutedEventArgs e)
        {
            BackgroundWorker bg = new BackgroundWorker();
            bg.DoWork += bg_DoWork;
            bg.RunWorkerCompleted += bg_RunWorkerCompleted;
            bg.RunWorkerAsync();
            BlogComment = (CommentBox as TextBox).Text;            
        }

        void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (Constants.CommentPosted == true)
            {
                Border frameBorder = (Border)VisualTreeHelper.GetChild(Application.Current.RootVisual, 0);
                TextBlock tb = frameBorder.FindName("Blog_Msg") as TextBlock;
                tb.Text = "Comment posted successfully";
                Popup Adc = frameBorder.FindName("pop") as Popup;
                Adc.IsOpen = true;
                Constants.CommentPosted = false;
                NavigationService.GoBack();
                //MessageBoxResult result = MessageBox.Show("Comment Posted successfully", "", MessageBoxButton.OK);
                //if (result == MessageBoxResult.OK)
                //{
                //    (CommentBox as TextBox).Text = string.Empty;
                //    Constants.CommentPosted = false;
                //    NavigationService.GoBack();
                //}
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("The user does not allow to create a comment", "", MessageBoxButton.OK);
                if (result == MessageBoxResult.OK)
                {
                    (CommentBox as TextBox).Text = string.Empty;
                    NavigationService.GoBack();
                }
            }
        }

        void bg_DoWork(object sender, DoWorkEventArgs e)
        {
            string Id=((SyndicationItem)Constants.SelectedSyndicationItem[0]).Id;
            PostToblog p = new PostToblog();
            p.UploadItem(BlogComment, auto, Id.Substring(Id.IndexOf('-') + 1, (Id.LastIndexOf('.') - (Id.IndexOf('-') + 1))), Id.Substring(Id.LastIndexOf('-') + 1));
            auto.WaitOne();
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            if (FeedType == "FaceBook")
            {
                btnPost_Click(null, null);
            }
            else if (FeedType == "Twitter")
            {
                btnPost1_Click(null, null);
            }
            else
            {
                btnPost2_Click(null, null);
            }
        }
        private void txtComment_Loaded(object sender, RoutedEventArgs e)
        {
            CommentBox = sender as TextBox;
        }

        private void txtComment1_Loaded(object sender, RoutedEventArgs e)
        {
            (sender as PhoneTextBox).Hint = "@" +((TwitterStatus)DataSource[0].item).User.ScreenName + " ";
            CommentBox = sender as PhoneTextBox;            
        }

        private void txtComment2_Loaded(object sender, RoutedEventArgs e)
        {
            CommentBox = sender as TextBox;
        }

        private void Image_ImageOpened(object sender, RoutedEventArgs e)
        {
            if((sender as Image).RenderSize.Height<100)
            {
                (sender as Image).Visibility = Visibility.Collapsed;
            }
        }

        private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            (sender as Image).Visibility = Visibility.Collapsed;
        }
    }
}